/*
 *
 * Copyright (C) 2012 Walter Lütgenau
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * 
 */
package offset.nodes.server.view.list;

import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author Walter Lütgenau
 */
public class IteratorList extends DummyList implements PageableList {

    Iterator results;
    List cache = new LinkedList();
    int pageSize = ListPager.DEFAULT_PAGE_SIZE;
    int pageStart = 0;
    ObjectWrapper objectWrapper = null;

    public IteratorList(Iterator results) {
        this.results = results;
    }

    public IteratorList(Iterator results, ObjectWrapper objectWrapper) {
        this(results);
        this.objectWrapper = objectWrapper;
    }

    public Object get(int index) {
        while (cache.size() < index + 1 + pageStart && results.hasNext()) { // fill cache only on demand
            Object result = results.next();
            cache.add(result);
        }

        if ( index + pageStart + 1 > cache.size())
            return null;
        
        Object object = cache.get(index+pageStart);
        
        // if there is a wrapper implementation, return this
        if ( objectWrapper != null && objectWrapper.isWrappedObject(object))
            return objectWrapper.wrapObject(object);

        // else, if this is not necessary (e.g. object is a bean), return object
        return object;
    }

    public int size() {
        return Math.min(Math.min(getPageSize(),getTotalSize()),getTotalSize()-pageStart);
    }

    public void setPageSize(int size) {
        this.pageSize = size;
    }
    
    public int getPageSize() {
        return pageSize;
    }

    public void setPageStart(int start) {
        if ( start < 0)
            return;
        if ( start > getTotalSize() - 1)
            return;
        this.pageStart = start;
    }
    
    public int getPageStart() {
        return pageStart;
    }
    
    public int getTotalSize() {
        if ( objectWrapper != null && objectWrapper.isWrappedObjectContainer(results))
            return objectWrapper.getTotalSize(results);
        return 0;
    }
    
}

